<!DOCTYPE html>
<html>
<head>
    <title>销售列表导出</title>
    <link rel="stylesheet" href="../static/css/ej.css">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        .export-container {
            max-width: 1200px;
            margin: 20px auto;
            padding: 20px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #333;
        }
        .form-group select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-sizing: border-box;
        }
        .submit-btn {
            background-color: #c0a36c;
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            margin-top: 20px;
        }
        .submit-btn:hover {
            background-color: #a88c5a;
        }
        .submit-btn:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        .loading {
            text-align: center;
            padding: 20px;
            color: #666;
        }
        .error {
            color: #d32f2f;
            padding: 10px;
            background-color: #ffebee;
            border-radius: 4px;
            margin: 10px 0;
        }
        .success {
            color: #2e7d32;
            padding: 10px;
            background-color: #e8f5e8;
            border-radius: 4px;
            margin: 10px 0;
        }
        .stock-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            font-size: 14px;
        }
        .stock-table th,
        .stock-table td {
            border: 1px solid #ddd;
            padding: 10px 8px;
            text-align: left;
            line-height: 1.4;
        }
        .stock-table th {
            background-color: #f8f9fa;
            font-weight: bold;
            color: #333;
            white-space: nowrap;
        }
        .stock-table tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        .stock-table tr:hover {
            background-color: #f0f8ff;
        }
        /* 列宽调整 */
        .stock-table th:nth-child(1),
        .stock-table td:nth-child(1) {
            width: 40px;
            text-align: center;
        }
        .stock-table th:nth-child(2),
        .stock-table td:nth-child(2) {
            width: 120px;
        }
        .stock-table th:nth-child(3),
        .stock-table td:nth-child(3) {
            width: 70px;
            text-align: center;
        }
        .stock-table th:nth-child(4),
        .stock-table td:nth-child(4) {
            width: 140px;
        }
        .stock-table th:nth-child(5),
        .stock-table td:nth-child(5) {
            width: 100px;
        }
        .stock-table th:nth-child(6),
        .stock-table td:nth-child(6) {
            width: 80px;
        }
        .stock-table th:nth-child(7),
        .stock-table td:nth-child(7) {
            width: 80px;
        }
        .stock-table th:nth-child(8),
        .stock-table td:nth-child(8) {
            width: 150px;
        }
        .stock-table th:nth-child(9),
        .stock-table td:nth-child(9),
        .stock-table th:nth-child(10),
        .stock-table td:nth-child(10),
        .stock-table th:nth-child(11),
        .stock-table td:nth-child(11),
        .stock-table th:nth-child(12),
        .stock-table td:nth-child(12),
        .stock-table th:nth-child(13),
        .stock-table td:nth-child(13),
        .stock-table th:nth-child(14),
        .stock-table td:nth-child(14),
        .stock-table th:nth-child(15),
        .stock-table td:nth-child(15) {
            width: 80px;
            text-align: right;
        }
        /* 数字列样式 */
        .stock-table td:nth-child(9),
        .stock-table td:nth-child(10),
        .stock-table td:nth-child(11),
        .stock-table td:nth-child(12),
        .stock-table td:nth-child(13),
        .stock-table td:nth-child(14),
        .stock-table td:nth-child(15) {
            font-family: 'Courier New', monospace;
            font-weight: 500;
        }
        .product-image {
            width: 60px;
            height: 60px;
            object-fit: cover;
            border-radius: 4px;
            border: 1px solid #ddd;
        }
        .export-options {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
        }
        .export-option {
            flex: 1;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .export-option:hover {
            background-color: #f8f9fa;
            border-color: #c0a36c;
        }
        .export-option.selected {
            background-color: #e8f5e8;
            border-color: #2e7d32;
        }
        .export-option h4 {
            margin: 0 0 10px 0;
            color: #333;
        }
        .export-option p {
            margin: 0;
            color: #666;
            font-size: 14px;
        }
    </style>
</head>
<body style="background-color:#fffbf6">
    
    <!-- 状态栏 -->
    {% include 'status_bar.html' %}
    
    <!-- 返回主菜单按钮 -->
    <div style="max-width: 1200px; margin: 20px auto 10px auto; padding: 0 20px;">
        <a href="/ej_index" class="btn btn-outline-secondary btn-sm" style="margin-bottom: 10px;">
            <i class="bi bi-arrow-left"></i> 返回主菜单
        </a>
    </div>
    
    <h2 style="max-width: 1200px; margin: 0 auto 20px auto; padding: 0 20px;">销售列表导出</h2>

    <div class="export-container">
        <!-- 选择操作按钮 -->
        <div style="margin-bottom: 20px; text-align: center;">
            <button id="selectAllBtn" class="btn btn-outline-primary btn-sm" style="margin-right: 10px;">
                <i class="bi bi-check-all"></i> 全选
            </button>
            <button id="deselectAllBtn" class="btn btn-outline-secondary btn-sm" style="margin-right: 10px;">
                <i class="bi bi-x-circle"></i> 全不选
            </button>
            <button id="exportBtn" class="submit-btn" disabled style="padding: 6px 12px; font-size: 14px;">
                <i class="bi bi-download"></i> 导出Excel
            </button>
        </div>

        <!-- 已选择记录计数显示 -->
        <div id="selectedCountAlert" style="display: none; margin-bottom: 15px; text-align: center;">
            <div class="alert alert-info py-2 mb-0" style="display: inline-block;">
                <i class="bi bi-check-circle"></i> 已选择 <span id="selectedCount">0</span> 条记录
            </div>
        </div>

        <!-- 筛选选项 -->
        <div class="form-group">
            <label>库存编号筛选</label>
            <select id="stock_filter">
                <option value="all">全部有效库存</option>
            </select>
        </div>

        <div id="loading" class="loading" style="display: none;">
            <i class="bi bi-arrow-repeat spinner"></i> 正在加载数据...
        </div>
        <div id="error" class="error" style="display: none;"></div>
        <div id="success" class="success" style="display: none;"></div>

        <!-- 库存表格 -->
        <div id="stockTableContainer" style="display: none;">
            <table class="stock-table">
                <thead>
                    <tr>
                        <th><input type="checkbox" id="selectAll"></th>
                        <th>库存编号</th>
                        <th>产品图片</th>
                        <th>产品ID</th>
                        <th>产品名称</th>
                        <th>类别</th>
                        <th>五行属性</th>
                        <th>材料</th>
                        <th>材料成本</th>
                        <th>手工成本</th>
                        <th>运输成本</th>
                        <th>其他成本</th>
                        <th>成本合计</th>
                        <th>可售数量</th>
                        <th>成本价</th>
                    </tr>
                </thead>
                <tbody id="stockTableBody"></tbody>
            </table>
        </div>
    </div>

    <script src="../static/js/common.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let stockData = []; // 存储所有库存数据

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 加载库存数据
            loadStockData();

            // 全选按钮点击事件
            document.getElementById('selectAllBtn').addEventListener('click', function() {
                const checkboxes = document.querySelectorAll('.stock-checkbox');
                checkboxes.forEach(checkbox => {
                    checkbox.checked = true;
                });
                document.getElementById('selectAll').checked = true;
                updateExportButtonState();
            });

            // 全不选按钮点击事件
            document.getElementById('deselectAllBtn').addEventListener('click', function() {
                const checkboxes = document.querySelectorAll('.stock-checkbox');
                checkboxes.forEach(checkbox => {
                    checkbox.checked = false;
                });
                document.getElementById('selectAll').checked = false;
                updateExportButtonState();
            });

            // 全选/取消全选
            document.getElementById('selectAll').addEventListener('change', function() {
                const checkboxes = document.querySelectorAll('.stock-checkbox');
                checkboxes.forEach(checkbox => {
                    checkbox.checked = this.checked;
                });
                updateExportButtonState();
            });

            // 导出按钮点击事件
            document.getElementById('exportBtn').addEventListener('click', function() {
                exportToExcel();
            });

            // 筛选器改变事件
            document.getElementById('stock_filter').addEventListener('change', function() {
                filterStockTable(this.value);
            });
        });

        // 加载库存数据
        function loadStockData() {
            const loading = document.getElementById('loading');
            const error = document.getElementById('error');
            
            loading.style.display = 'block';
            error.style.display = 'none';

            fetch('/get_export_stock_data')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    loading.style.display = 'none';
                    if (data.success && data.data) {
                        stockData = data.data;
                        console.log('获取到的库存数据：',stockData);
                        initStockFilterOptions();
                        renderStockTable();
                        document.getElementById('stockTableContainer').style.display = 'block';
                    } else {
                        throw new Error(data.message || '数据格式错误');
                    }
                })
                .catch(error => {
                    loading.style.display = 'none';
                    error.style.display = 'block';
                    error.textContent = '加载库存数据失败: ' + error.message;
                });
        }

        // 初始化库存筛选选项
        function initStockFilterOptions() {
            const stockFilter = document.getElementById('stock_filter');
            
            // 清空现有选项（保留"全部有效库存"）
            while (stockFilter.options.length > 1) {
                stockFilter.remove(1);
            }
            
            // 添加所有有效库存选项
            stockData.forEach(stock => {
                const option = document.createElement('option');
                option.value = stock.stock_id;
                option.textContent = `${stock.stock_id} (可用: ${stock.available_qty})`;
                stockFilter.appendChild(option);
            });
        }

        // 渲染库存表格
        function renderStockTable() {
            const tbody = document.getElementById('stockTableBody');
            tbody.innerHTML = '';
            
            stockData.forEach(stock => {
                const row = document.createElement('tr');

                    // 拼接材料信息
                    const materials = [
                        stock.major_material,
                        stock.second_material,
                        stock.third_material,
                        stock.accessories_material
                    ].filter(material => material && material.trim() !== '');
                    
                    const materials_str = materials.join('，');

                    // 拼接类别信息
                    const categories = [
                        stock.type_1,
                        stock.type_2
                    ].filter(category => category && category.trim() !== '');
                    
                    const categories_str = categories.join('-');


                
                // 计算成本合计
                const materialCost = parseFloat(stock.material_price || 0);
                const manualCost = parseFloat(stock.manual_price || 0);
                const transferCost = parseFloat(stock.transfer_price || 0);
                const otherCost = parseFloat(stock.other_price || 0);
                const totalCost = materialCost + manualCost + transferCost + otherCost;
                
                // 计算成本价（成本合计 / 数量）
                const availableQty = parseFloat(stock.available_qty || 1);
                const costPrice = availableQty > 0 ? ((totalCost +40)*availableQty).toFixed(2) : '0.00';
                
                row.innerHTML = `
                    <td>
                        <input type="checkbox" class="stock-checkbox" data-stock-id="${stock.stock_id}">
                    </td>
                    <td>${stock.stock_id || ''}</td>
                    <td>
                        ${stock.product_id ? `
                        <img src="/serve_jade_image?product_id=${stock.product_id}" 
                             alt="产品图片" class="product-image" 
                             onerror="this.style.display='none'">
                        ` : ''}
                    </td>
                    <td>${stock.product_id || ''}</td>
                    <td>${stock.product_name || ''}</td>
                    <td>${categories_str || ''}</td>
                    <td>${stock.wu_xings || ''}</td>
                    <td>${materials_str || ''}</td>
                    <td>${materialCost.toFixed(2)}</td>
                    <td>${manualCost.toFixed(2)}</td>
                    <td>${transferCost.toFixed(2)}</td>
                    <td>${otherCost.toFixed(2)}</td>
                    <td>${totalCost.toFixed(2)}</td>
                    <td>${stock.available_qty || 0}</td>
                    <td>${costPrice}</td>
                `;
                
                tbody.appendChild(row);
            });
            
            // 为所有复选框添加事件监听
            document.querySelectorAll('.stock-checkbox').forEach(checkbox => {
                checkbox.addEventListener('change', updateExportButtonState);
            });
            
            updateExportButtonState();
        }

        // 筛选库存表格
        function filterStockTable(stockId) {
            const tbody = document.getElementById('stockTableBody');
            const rows = tbody.querySelectorAll('tr');
            
            rows.forEach(row => {
                const checkbox = row.querySelector('.stock-checkbox');
                const rowStockId = checkbox ? checkbox.dataset.stockId : '';
                
                if (stockId === 'all' || stockId === rowStockId) {
                    row.style.display = '';
                } else {
                    row.style.display = 'none';
                }
            });
        }

        // 更新导出按钮状态
        function updateExportButtonState() {
            const exportBtn = document.getElementById('exportBtn');
            
            // 导出选中选项，需要至少选中一个
            const selectedCount = document.querySelectorAll('.stock-checkbox:checked').length;
            exportBtn.disabled = selectedCount === 0;
            
            // 更新已选择记录计数显示
            updateSelectedCountDisplay(selectedCount);
        }

        // 更新已选择记录计数显示
        function updateSelectedCountDisplay(count) {
            const countElement = document.getElementById('selectedCount');
            const alertElement = document.getElementById('selectedCountAlert');
            
            countElement.textContent = count;
            
            if (count > 0) {
                alertElement.style.display = 'block';
            } else {
                alertElement.style.display = 'none';
            }
        }

        // 导出到Excel
        function exportToExcel() {
            const exportBtn = document.getElementById('exportBtn');
            const loading = document.getElementById('loading');
            const error = document.getElementById('error');
            const success = document.getElementById('success');
            
            // 检查是否有选中的行
            const selectedCount = document.querySelectorAll('.stock-checkbox:checked').length;
            if (selectedCount === 0) {
                error.style.display = 'block';
                error.textContent = '请至少选择一行数据进行导出！';
                setTimeout(() => {
                    error.style.display = 'none';
                }, 3000);
                return;
            }

            exportBtn.disabled = true;
            exportBtn.innerHTML = '<i class="bi bi-arrow-repeat spinner"></i> 导出中...';
            loading.style.display = 'block';
            error.style.display = 'none';
            success.style.display = 'none';

            // 准备导出数据 - 只导出选中的数据
            let exportData = [];
            const selectedCheckboxes = document.querySelectorAll('.stock-checkbox:checked');
            
            selectedCheckboxes.forEach(checkbox => {
                const stockId = checkbox.dataset.stockId;
                const stock = stockData.find(s => s.stock_id === stockId);
                if (stock) {
                    // 拼接材料信息
                    const materials = [
                        stock.major_material,
                        stock.second_material,
                        stock.third_material,
                        stock.accessories_material
                    ].filter(material => material && material.trim() !== '');
                    
                    const materials_str = materials.join('，');

                    const categories = [
                        stock.type_1,
                        stock.type_2
                    ].filter(category => category && category.trim() !== '');
                    
                    const categories_str = categories.join('-');

                    exportData.push({
                        stock_id: stock.stock_id,
                        product_id: stock.product_id,
                        product_name: stock.product_name,
                        category: categories_str,
                        wuxing: stock.wu_xings,
                        material: materials_str,
                        material_price: parseFloat(stock.material_price || 0).toFixed(2),
                        manual_price: parseFloat(stock.manual_price || 0).toFixed(2),
                        transfer_price: parseFloat(stock.transfer_price || 0).toFixed(2),
                        other_price: parseFloat(stock.other_price || 0).toFixed(2),
                        total_cost: (parseFloat(stock.material_price || 0) + 
                                    parseFloat(stock.manual_price || 0) + 
                                    parseFloat(stock.transfer_price || 0) + 
                                    parseFloat(stock.other_price || 0)).toFixed(2),
                        available_qty: stock.available_qty,
                        cost_price: (parseFloat(stock.available_qty || 1) > 0 ? 
                                    ((parseFloat(stock.material_price || 0) + 
                                      parseFloat(stock.manual_price || 0) + 
                                      parseFloat(stock.transfer_price || 0) + 
                                      parseFloat(stock.other_price || 0)) / 
                                     parseFloat(stock.available_qty || 1)).toFixed(2) : '0.00')
                    });
                }
            });

            // 发送导出请求
            fetch('/export_sale_excel', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    stock_data: exportData
                })
            })
            .then(response => {
                loading.style.display = 'none';
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                return response.blob();
            })
            .then(blob => {
                // 创建下载链接
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.style.display = 'none';
                a.href = url;
                a.download = `销售列表_${new Date().toISOString().slice(0, 10)}.xlsx`;
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
                document.body.removeChild(a);
                
                success.style.display = 'block';
                success.textContent = '导出成功！文件已开始下载。';
            })
            .catch(error => {
                loading.style.display = 'none';
                error.style.display = 'block';
                error.textContent = '导出失败: ' + error.message;
            })
            .finally(() => {
                exportBtn.disabled = false;
                exportBtn.innerHTML = '<i class="bi bi-download"></i> 导出Excel';
            });
        }

        // 显示错误信息
        function showError(message) {
            const error = document.getElementById('error');
            error.style.display = 'block';
            error.textContent = message;
            
            // 3秒后自动隐藏错误信息
            setTimeout(() => {
                error.style.display = 'none';
            }, 3000);
        }

        // 显示成功信息
        function showSuccess(message) {
            const success = document.getElementById('success');
            success.style.display = 'block';
            success.textContent = message;
            
            // 3秒后自动隐藏成功信息
            setTimeout(() => {
                success.style.display = 'none';
            }, 3000);
        }
    </script>
</body>
</html>
